package com.jdone.compus.model;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.jdone.compus.enums.OrderStatus;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import javax.persistence.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.ThreadLocalRandom;

@Data
@Entity
@Table(name = "blow_usage_records")
@ApiModel(value = "吹风订单实体类")
public class BlowUsageRecord {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(length = 64)
    @ApiModelProperty(value = "业务订单号")
    private String businessOrderNo;


    @ApiModelProperty(value = "退款单号")
    @Column(name = "out_refund_no")
    private String outRefundNo;

    @ApiModelProperty(value = "关联的设备实体")
    @JsonIgnore
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "device_id", insertable = false, updatable = false)
    private BlowDevice device;

    @ApiModelProperty(value = "设备id")
    @Column(name = "device_id")
    private Long deviceId;

    @ApiModelProperty("使用设备的所属IMEI")
    @Column(name = "imei_record_id", length = 64)
    private String imei;

    @ApiModelProperty("使用设备的所属生产厂家")
    @Column(length = 128)
    private String manufacturer;

    @ApiModelProperty(value = "使用人姓名")
    @Column(name = "user_name", length = 32)
    private String username;

    @ApiModelProperty(value = "账户")
    @Column(name = "user_account", length = 64)
    private String userAccount;

    @ApiModelProperty(value = "类型")
    @Column(name = "user_type", length = 32)
    private String userType;

    @ApiModelProperty(value = "电话")
    @Column(name = "user_phone", length = 32)
    private String userPhone;

    @ApiModelProperty(value = "订单开始时间")
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
    @Column(name = "borrow_time")
    private LocalDateTime borrowTime;

    @ApiModelProperty(value = "订单结束时间")
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
    @Column(name = "return_time")
    private LocalDateTime returnTime;

    @ApiModelProperty(value = "订单分钟数")
    @Column()
    private Integer minutes;

    @ApiModelProperty(value = "订单金额")
    @Column(precision = 10, scale = 2)
    private BigDecimal fee;

    @Transient
    @ApiModelProperty(value = "订单金额")
    private Double orderAmount;

    @Enumerated(EnumType.STRING)
    @Column(length = 24)
    @ApiModelProperty(value = "'CREATED', 'PAID', 'USED','CANCELLED' 订单的状态")
    private OrderStatus orderStatus;

    @ApiModelProperty(value = "创建时间")
    @Column(name = "created_at", updatable = false)
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime createdAt;

    @ApiModelProperty(value = "修改时间")
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
    @Column(name = "updated_at")
    private LocalDateTime updatedAt;

    @PrePersist
    protected void onCreate() {
        LocalDateTime now = LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS);
        this.createdAt = now;
        this.updatedAt = now;
        this.orderStatus = OrderStatus.CREATED;

        // 自动生成业务订单号
        if (this.businessOrderNo == null || this.businessOrderNo.isEmpty()) {
            this.businessOrderNo = generateOrderNo(now);
        }
    }

    @PreUpdate
    protected void onUpdate() {
        this.updatedAt = LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS);
    }

    /**
     * 生成 18 位订单号：8 位日期（yyyyMMdd）+ 10 位随机数
     */
    private String generateOrderNo(LocalDateTime dateTime) {
        // 1. 日期部分：yyyyMMdd
        String datePart = dateTime.format(DateTimeFormatter.ofPattern("yyyyMMdd"));

        // 2. 随机数部分：10 位，前面补足 0
        long randomNum = ThreadLocalRandom.current().nextLong(0, 1_000_000_0000L);
        String randomPart = String.format("%010d", randomNum);

        return datePart + randomPart;
    }
}
